import WxRouter from 'router';
const app = getApp();

function _ModelForGetLocationModel(resolve, reject) {
  wx.showModal({
    title: '',
    content: '检测到你未打开地理位置的权限，是否前往开启',
    confirmText: '前往开启',
    cancelText: "手动定位",
    success(res) {
      if (res.confirm) {
        //成功的时候只执行一次（通过手动的时候就没执行了）
        wx.openSetting({
          success(res) {
            wx.authorize({
              scope: 'scope.userLocation',
              success() {
                resolve("toggle");
              },
              fail() {
                console.log("fail");
                _ModelForGetLocationModel(resolve, reject);
              }
            })
          }
        })
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    }
  })
}

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}


const getLocation=function() {
  return new Promise(function (resolve, reject) {
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        console.log(`getLocation:${res}`)
        app.setStorage('location', res);
        resolve(res);
      },
      fail(res) {
        _ModelForGetLocationModel(resolve,reject);
      }
    })
  })
}


const openLocation=function(params){
  wx.openLocation({
    latitude: params.latitude,
    longitude: params.longitude,
    name: params.name || '',
    address: params.address || '',
    scale: params.scale || 18
  })
}


module.exports = {
  formatTime: formatTime,
  getLocation: getLocation,
  openLocation: openLocation,
  $router:new WxRouter()
}
